package cn.itrip.controller;

import cn.itrip.beans.dto.Dto;
import cn.itrip.beans.pojo.ItripHotelOrder;
import cn.itrip.common.DtoUtil;
import cn.itrip.config.WXPayConfig;
import cn.itrip.service.OrderService;
import cn.itrip.config.WXPayConfig;
import cn.itrip.service.OrderService;
import cn.itrip.wx.WXPayRequest;
import cn.itrip.wx.WXPayUtil;
import cn.itrip.wx.WXPayConstants;
import cn.itrip.wx.WXPayUtil;
import io.swagger.annotations.ApiOperation;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by zezhong.shang on 17-8-11.
 */
@Controller
@RequestMapping("/api/wxpay")
public class WxPaymentController {

    private Logger logger = Logger.getLogger(WxPaymentController.class);

    @Autowired
    private OrderService orderService;

    @Autowired
    private WXPayConfig wxPayConfig;

    @ApiOperation(value = "订单微信支付", httpMethod = "GET",
            protocols = "HTTP", produces = "application/xml", consumes = "application/x-www-form-urlencoded",
            response = String.class,
            notes = "客户端提交订单支付请求，对该API的返回结果不用处理，" +
                    "浏览器将自动跳转至微信支付二维码页面。<br><b>请使用普通表单提交，" +
                    "不能使用ajax异步提交。</b>")
    @RequestMapping(value = "/createqccode/{orderNo}", method = RequestMethod.GET)
    @ResponseBody
    public Dto createQcCode(@PathVariable String orderNo, HttpServletResponse response) {
      try{
          ItripHotelOrder order=orderService.loadItripHotelOrder(orderNo);
          WXPayRequest wxPayRequest=new WXPayRequest(this.wxPayConfig);
          HashMap param=new HashMap();
          param.put("body","爱旅行项目订单支付");
          param.put("out_trade_no",orderNo);
          param.put("device_info","");
          param.put("total_fee","1");
        Map resultMap=wxPayRequest.unifiedorder(param);
        if (resultMap.get("return_code").equals("SUCCESS")&&resultMap.get("result_code").equals("SUCCESS")){
            Map result=new HashMap();
            result.put("hotelName",order.getHotelName());
            result.put("payAmount",order.getPayAmount());
            result.put("count",order.getCount());
            result.put("roomId",order.getRoomId());
            result.put("codeUrl",resultMap.get("code_url"));
            return DtoUtil.returnDataSuccess(result);
        }else {
            return DtoUtil.returnFail(resultMap.get("return_msg").toString(),"100002");
        }
      }catch (Exception e){
          e.printStackTrace();
      }

        return DtoUtil.returnFail("发生错误","100001");
    }

    @RequestMapping(value = "/notify", method = RequestMethod.POST)
    public void paymentCallBack(HttpServletRequest request, HttpServletResponse response) throws IOException {
          try{
              StringBuffer stringBuffer=new StringBuffer();
              InputStream inputStream=request.getInputStream();
              BufferedReader reader=new BufferedReader(new InputStreamReader(inputStream,"UTF-8"));
              String temp;
              while ((temp=reader.readLine())!=null){
                  stringBuffer.append(temp);
              }
              reader.close();
              inputStream.close();
              Map<String,String > resultMap=WXPayUtil.xmlToMap(stringBuffer.toString());
             boolean flag= WXPayUtil.isSignatureValid(resultMap,wxPayConfig.getKey(),WXPayConstants.SignType.HMACSHA256);
              if (flag) {
                  if (resultMap.get("return_code").equals("SUCCESS") && resultMap.get("result_code").equals("SUCCESS")) {
                    String out_trade_no=resultMap.get("out_trade_no");
                      String trade_no=resultMap.get("prepay_id");
                        orderService.paySuccess(out_trade_no,2,trade_no);
                  }
              }
          }catch (Exception e){
              e.printStackTrace();
          }finally {
              Map<String,String> resultMap=new HashMap<>();
              resultMap.put("return_code","SUCCESS");
              resultMap.put("return_msg","SUCESS");
              try{
                  String respXml=WXPayUtil.generateSignedXml(resultMap,wxPayConfig.getKey(),WXPayConstants.SignType.HMACSHA256);
                    response.getWriter().write(respXml);
                    response.getWriter().flush();
              }catch (Exception e){
                  e.printStackTrace();
              }
          }

    }

    /**
     * 微信支付轮询订单，查看订单是否支付成功
     *
     * @param orderNo
     * @return
     */
    @ApiOperation(value = "订单微信支付刷单程序", httpMethod = "GET",
            protocols = "HTTP", produces = "application/xml", consumes = "application/x-www-form-urlencoded",
            response = String.class,
            notes = "前端用户检测订单是否成功的接口<br>如果订单状态为2则代表订单支付成功<b></b>")
    @RequestMapping(value = "/queryorderstatus/{orderNo}", method = RequestMethod.GET)
    @ResponseBody
    public Dto<ItripHotelOrder> queryOrderIsSuccess(@PathVariable String orderNo) {
       try{
           ItripHotelOrder order = orderService.loadItripHotelOrder(orderNo);
           return DtoUtil.returnDataSuccess(order);
       }catch (Exception e){
           e.printStackTrace();
       }

        return  DtoUtil.returnFail("查询失败","100003");
    }
}
